<template>
  <div class="chart-html-container">
    <iframe
      ref="chartIframe"
      :srcdoc="htmlContent"
      frameborder="0"
      scrolling="no"
      class="chart-iframe"
    ></iframe>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'

const props = defineProps({
  htmlContent: {
    type: String,
    required: true
  }
})

const chartIframe = ref(null)

// 调整 iframe 和图表大小（使用 requestAnimationFrame 优化性能）
let resizeRequestId = null
let resizeObserver = null

const resizeIframe = () => {
  if (resizeRequestId) {
    cancelAnimationFrame(resizeRequestId)
  }
  
  resizeRequestId = requestAnimationFrame(() => {
    if (chartIframe.value) {
      const iframe = chartIframe.value
      const container = chartIframe.value.parentElement
      
      if (container) {
        // 获取容器实际尺寸（包含 padding）
        const containerRect = container.getBoundingClientRect()
        const containerWidth = containerRect.width || container.clientWidth
        const containerHeight = containerRect.height || container.clientHeight
        
        // 只有当尺寸变化时才更新，避免不必要的重绘
        const currentWidth = parseInt(iframe.style.width) || 0
        const currentHeight = parseInt(iframe.style.height) || 0
        
        if (Math.abs(currentWidth - containerWidth) > 1 || Math.abs(currentHeight - containerHeight) > 1) {
          // 设置 iframe 大小为容器大小
          iframe.style.width = containerWidth + 'px'
          iframe.style.height = containerHeight + 'px'
        }
        
        // 尝试调整图表大小（跨域可能无法访问）
        try {
          const iframeWindow = iframe.contentWindow
          if (iframeWindow && iframeWindow.echarts) {
            const iframeDoc = iframe.contentDocument || iframeWindow.document
            if (iframeDoc) {
              // 查找所有的图表实例并调整大小
              const chartElements = iframeDoc.querySelectorAll('[id^="chart_"]')
              chartElements.forEach(el => {
                try {
                  const chartInstance = iframeWindow.echarts.getInstanceByDom(el)
                  if (chartInstance && !chartInstance.isDisposed()) {
                    chartInstance.resize({
                      width: containerWidth,
                      height: containerHeight
                    })
                  }
                } catch (e) {
                  // 忽略单个图表调整错误
                }
              })
            }
          }
        } catch (e) {
          // 跨域限制或未加载完成，忽略错误
        }
      }
    }
    
    resizeRequestId = null
  })
}

onMounted(() => {
  const iframe = chartIframe.value
  if (iframe) {
    // 初始大小设置
    resizeIframe()
    
    iframe.onload = () => {
      // 延迟执行，确保内容完全加载
      setTimeout(() => {
        resizeIframe()
        // 再次延迟执行，确保图表已经初始化
        setTimeout(() => {
          resizeIframe()
        }, 300)
        // 第三次延迟，确保所有渲染完成
        setTimeout(() => {
          resizeIframe()
        }, 600)
      }, 150)
      
      // 使用 ResizeObserver 监听容器大小变化（更精确）
      if (window.ResizeObserver) {
        const container = chartIframe.value.parentElement
        if (container) {
          resizeObserver = new ResizeObserver((entries) => {
            // 使用防抖避免频繁调用
            resizeIframe()
          })
          resizeObserver.observe(container)
        }
      }
      
      // 监听窗口大小变化（备用方案）
      window.addEventListener('resize', resizeIframe, { passive: true })
    }
    
    // 即使 iframe 还没加载完成，也定期检查并设置大小
    const initInterval = setInterval(() => {
      if (iframe.contentDocument && iframe.contentDocument.readyState === 'complete') {
        clearInterval(initInterval)
        resizeIframe()
      }
    }, 100)
    
    // 5秒后清除检查
    setTimeout(() => {
      clearInterval(initInterval)
    }, 5000)
  }
})

watch(() => props.htmlContent, () => {
  if (chartIframe.value) {
    resizeIframe()
  }
})

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
  window.removeEventListener('resize', resizeIframe)
  if (resizeRequestId) {
    cancelAnimationFrame(resizeRequestId)
    resizeRequestId = null
  }
})
</script>

<style scoped>
.chart-html-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  min-width: 0;
  min-height: 0;
  display: flex;
  align-items: stretch;
  justify-content: stretch;
}

.chart-iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
  background: transparent;
  flex: 1;
  min-width: 0;
  min-height: 0;
}
</style>

